//
//  WBEmoticonManager.m
//  sinaWeibo
//
//  Created by 李江波 on 2016/11/23.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//

#import "WBEmoticonManager.h"
#import "WBEmoticon.h"
#import <YYModel.h>
#define emoticonsPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"emoticons.plist"]

@interface WBEmoticonManager ()

@property(nonatomic ,strong) NSMutableArray<WBEmoticon *> *recentEmoticons;

@property(nonatomic ,strong) NSArray *defaultEmoticons;
@property(nonatomic ,strong) NSArray *emojiEmoticons;
@property(nonatomic ,strong) NSArray *lxhEmoticons;

@end

static NSInteger emoticonPageCount = 20;

@implementation WBEmoticonManager

-(NSArray<WBEmoticon *> *)recentEmoticons{

    if (nil == _recentEmoticons) {
        
        _recentEmoticons = [NSKeyedUnarchiver unarchiveObjectWithFile:emoticonsPath];
        
        if (_recentEmoticons == nil) {
            
            _recentEmoticons = @[[WBEmoticon new]].mutableCopy;
        }
    }
    return _recentEmoticons;
}


-(NSBundle *)emoticonBundle{

    if (nil == _emoticonBundle) {
        //1. 获取Emoticons.bundle的路径
        NSString *path = [[NSBundle mainBundle] pathForResource:@"Emoticons.bundle" ofType:nil];
        
        _emoticonBundle = [[NSBundle alloc]initWithPath:path];
    }
    return _emoticonBundle;
}

static id _instance;
+(instancetype)shared{

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        _instance = [[self alloc]init];
    });
    return _instance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self getEmoticons];
    }
    return self;
}


-(void)getEmoticons{

     //默认表情的数组
    _defaultEmoticons = [self loadEmoticon:@"default/info.plist"];
    //Emoji表情的数组
    _emojiEmoticons = [self loadEmoticon:@"emoji/info.plist"];
    //Lxh表情的数组
    _lxhEmoticons = [self loadEmoticon:@"lxh/info.plist"];
    
    self.allEmoticons = @[@[self.recentEmoticons],[self emoticonPages:_defaultEmoticons], [self emoticonPages:_emojiEmoticons] , [self emoticonPages:_lxhEmoticons]];
    
    
}

-(NSArray *)emoticonPages:(NSArray<WBEmoticon *>*)array {

    //按照每页20个表情 对模型数组进行切割(分页)
    // 108  -> 每页20 个 --> 6页
    NSInteger pageCount = (array.count - 1) / emoticonPageCount + 1;
    //分页截取
    NSMutableArray *arrayM = [NSMutableArray array];
    
    for (int i = 0; i < pageCount; i ++) {
        
        NSInteger loc = i * emoticonPageCount ;
        NSInteger len = emoticonPageCount;
        
        if ((loc + len) > array.count) {
            
            len = array.count - loc;
        }
        
        NSArray *pageArray = [array subarrayWithRange:NSMakeRange(loc, len)];
        
        [arrayM addObject:pageArray];
    }
    
    return arrayM.copy;
}

-(NSArray<WBEmoticon *> *)loadEmoticon:(NSString *)path{

    //使用bundle的pathForResource方法读取bundle对象中的文件
    NSString *infoPath = [self.emoticonBundle pathForResource:path ofType:nil];
    
    //读取数组类型的plist文件
    NSArray *array = [NSArray arrayWithContentsOfFile:infoPath];
    
    NSMutableArray *arrayM = [NSMutableArray array];
    for (NSDictionary *dict in array) {
        
        WBEmoticon *model = [WBEmoticon yy_modelWithDictionary:dict];
        
        model.imagePath = [NSString stringWithFormat:@"%@/%@",[path stringByDeletingLastPathComponent],model.png];
        
        [arrayM addObject:model];
    }
    
    
    return arrayM.copy;
}


#pragma mark : - 保存表情，存档
-(void)saveEmoticons:(WBEmoticon *)emoticon{

    
    [self.recentEmoticons enumerateObjectsUsingBlock:^(WBEmoticon * _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (model.type) {
            
            if ([model.code isEqualToString:emoticon.code]) {
                
                [self.recentEmoticons removeObjectAtIndex:idx];
            }
        }else{
            
            if ([model.chs isEqualToString:emoticon.chs]) {
                
                [self.recentEmoticons removeObjectAtIndex:idx];
            }
        }
    }];
    
    //不能用containsObject: 这是地址的比较。首次会有问题
//    if ([self.recentEmoticons isEqual:emoticon]) {
//        
//        [self.recentEmoticons removeObject:emoticon];
//    }
    
    /**
     1. 如果两个表情模型都是图片表情或都是emoji表情，才有对比的必要
     2. 如果是图片表情，要对比png
     3. 如果是emoji表情，要对比code
     */
    
//    if (emoticon.type) {
//        
//        if ([self.emojiEmoticons containsObject:emoticon]) {
//            
//            [self.recentEmoticons removeObject:emoticon];
//        }
//    }else{
//        
//        if ([self.defaultEmoticons containsObject:emoticon] || [self.lxhEmoticons containsObject:emoticon]) {
//            
//            [self.recentEmoticons removeObject:emoticon];
//        }
//    }
    
    [self.recentEmoticons insertObject:emoticon atIndex:0];
    //如果大于20 就删除最后一个
    if (self.recentEmoticons.count > 20) {
        
        [self.recentEmoticons removeLastObject];
    }
    
    [NSKeyedArchiver archiveRootObject:self.recentEmoticons toFile:emoticonsPath];
    //显示到最近的分组这一组 如何显示  需要刷新第0组
    // 当两个类之间没有明前前后关系  使用通知是最好的方式
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"KsaveRecentEmoticon" object:nil];
}

-(WBEmoticon *)findEmoticonByImageName:(NSString *)str{

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"chs=%@",str];
    NSArray *result = [self.defaultEmoticons filteredArrayUsingPredicate:predicate];
    
    if (result > 0) {
        
        return result.firstObject;
    }
    
    NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"chs=%@",str];
    NSArray *result2 = [self.lxhEmoticons filteredArrayUsingPredicate:predicate2];
    
    if (result2.count > 0) {
        
        return result2.firstObject;
    }
    
    return nil;
}

@end







